package com.dpiinc.TechPage.pen.activity

import android.content.*
import android.os.Bundle
import androidx.core.content.ContextCompat
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import com.dpiinc.TechPage.BaseActivity
import com.dpiinc.TechPage.R
import com.dpiinc.TechPage.activity.EditNoteActivity
import com.dpiinc.TechPage.constants.RxbusEvents
import com.dpiinc.TechPage.pen.dialog.ServiceDialog
import com.dpiinc.TechPage.pen.fragment.ScanPenFragment
import com.dpiinc.TechPage.widget.CommDialog
import com.dpiinc.TechPage.widget.LoadingView
import com.beiji.lib.pen.PenLog
import com.beiji.lib.pen.PenManager
import com.beiji.lib.pen.PenScanner
import com.beiji.lib.pen.constants.PenBusTag
import com.beiji.lib.pen.constants.PenConnectState
import com.beiji.lib.pen.model.DotUnit
import com.beiji.lib.pen.model.PenInfo
import com.hwangjr.rxbus.RxBus
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import com.hwangjr.rxbus.thread.EventThread
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.Permission
import kotlinx.android.synthetic.main.activity_connect_pen.*
import kotlinx.android.synthetic.main.connect_failed_layout.*


/**
 * 连接数码笔页面
 * Created by X on 2018/6/14.
 */
class ConnectPenActivity : BaseActivity(), ScanPenFragment.OnListFragmentInteractionListener, View.OnClickListener {

    companion object {
        private const val TAG = "ConnectPenActivity"
        const val PARAM_FROM = "param_from"
        const val FROM_NOTE_LIST = 0
        const val FROM_EDIT_NOTE = 1

        private const val STEP_PREPARE = 1
        private const val STEP_SEARCH_AND_CONNECT = 2
        private const val STEP_CONNECT_SUCCESS = 3
        private const val STEP_CONNECT_FAILED = 4
        private const val STEP_DISCONNECT = 5
    }

    private var curStep = STEP_PREPARE
    private val scanPenFragment = ScanPenFragment.newInstance()
    var isRegister: Boolean = false
    private var mFrom = FROM_NOTE_LIST
    private var lastClickTime: Long = 0L
    override fun onListFragmentInteraction(pen: PenInfo) {
        if (pen.macAddress.isEmpty()) {
            return
        }
        if (isFastClick()) {
            PenManager.instance.connectPen(pen.name, pen.macAddress)
            LoadingView.createLoadingViewAndShow(this, 0, null)
        }
    }

    fun isFastClick(): Boolean {
        var flag = false
        var curClickTime = System.currentTimeMillis()
        if (curClickTime - lastClickTime >= 1000) {
            flag = true
        }
        lastClickTime = curClickTime
        return flag
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_connect_pen)
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayShowTitleEnabled(false)
        RxBus.get().register(this)
        toolbar.setNavigationOnClickListener {
            onBackPressed()
        }
        mFrom = intent.getIntExtra(PARAM_FROM, FROM_NOTE_LIST)
        btn_reconnect.setOnClickListener {
            changeStep(STEP_PREPARE, false)
        }
//        checkStoragePermission()
        PenManager.instance.cancelAutoConnectTask()
//        PenScanner.instance.doScan()

        btn_next.setOnClickListener(this)
        btn_pen_connect.setOnClickListener(this)

    }

    private fun checkStoragePermission() {
        AndPermission.with(this)
                .runtime()
                .permission(Permission.Group.STORAGE)
                //拒绝一次之后的提示
                .rationale { context, _, executor ->
                    PenLog.e("rationale")
                    val builder = CommDialog.Builder()
                    builder.setMessage(getString(R.string.need_storage_authority))
                            .setLeftButton(getString(R.string.need_authority_refuse), DialogInterface.OnClickListener { dialogInterface, _ ->
                                dialogInterface.dismiss()
                                finish()
                            })
                            .setRightButton(getString(R.string.need_authority_ok), DialogInterface.OnClickListener { dialogInterface, _ ->
                                dialogInterface.dismiss()
                                executor.execute()
                            })
                    builder.build().show(supportFragmentManager)
                }
                //申请被拒绝
                .onDenied { permissions ->
                    PenLog.e("onDenied")
                    //被拒绝，且选择了不再提醒之后，需要提示用户去设置页面手动打开
                    if (AndPermission.hasAlwaysDeniedPermission(this, permissions)) {
                        val builder = CommDialog.Builder()
                        builder.setMessage(getString(R.string.need_storage_authority_real))
                                .setLeftButton(getString(R.string.need_authority_refuse), DialogInterface.OnClickListener { dialogInterface, _ ->
                                    dialogInterface.dismiss()
                                    finish()
                                })
                                .setRightButton(getString(R.string.need_authority_ok2), DialogInterface.OnClickListener { dialogInterface, _ ->
                                    dialogInterface.dismiss()
                                    AndPermission.with(this)
                                            .runtime()
                                            .setting()
                                            .onComeback {
                                                if (!AndPermission.hasPermissions(this, Permission.Group.STORAGE)) {
                                                    finish()
                                                }
                                            }
                                            .start()
                                })
                        builder.build().show(supportFragmentManager)
                    } else {
                        checkStoragePermission()
                    }
                }
                .start()
    }

    override fun onClick(v: View?) {
        v ?: return
        when (v.id) {
            R.id.btn_next -> {
                changeStep(STEP_SEARCH_AND_CONNECT, true)
            }
            R.id.btn_pen_connect -> {
                RxBus.get().post(RxbusEvents.EVENT_CLOSE_PEN_STATUS_PAGE)
                finish()
//                if (mFrom == FROM_NOTE_LIST) {
//                    startActivity(Intent(this, NoteListActivity::class.java))
//                }
            }
        }
    }

    private fun changeStep(step: Int, forward: Boolean) {
        curStep = step
        when (step) {
            //连接准备
            STEP_PREPARE -> {
                ll_connect.visibility = View.GONE
                iv_connect.visibility = View.GONE
                ll_connect_status.visibility = View.VISIBLE
                connect_pen_introduce_layout.visibility = View.VISIBLE
                connect_failed_layout.visibility = View.GONE
                ll_pen_connect.visibility = View.GONE
                tv_hint.text = getText(R.string.label_connect_pen_hint_1)
                tv_hint.setTextColor(ContextCompat.getColor(this, R.color.connect_pen_hint))
                tv_sub_hint.text = getText(R.string.label_connect_pen_sub_hint_1)
                ll_blue.visibility = View.VISIBLE
                progress_bar.progress = 33
                supportFragmentManager.popBackStackImmediate()
//                detachFragment(scanPenFragment)
            }
            //搜索智能笔
            STEP_SEARCH_AND_CONNECT -> {
                ll_connect.visibility = View.GONE
                iv_connect.visibility = View.GONE
                ll_connect_status.visibility = View.VISIBLE
                fragment_container.visibility = View.VISIBLE
                connect_pen_introduce_layout.visibility = View.GONE
                connect_failed_layout.visibility = View.GONE
                ll_pen_connect.visibility = View.GONE
                if (forward) {
                    addFragment(R.id.fragment_container, scanPenFragment, "scan")
                } else {
                    replaceFragment(R.id.fragment_container, scanPenFragment, "scan")
                }
                tv_hint.text = getText(R.string.label_connect_pen_hint_2)
                tv_hint.setTextColor(ContextCompat.getColor(this, R.color.connect_pen_hint))
                tv_sub_hint.text = getText(R.string.label_connect_pen_sub_hint_2)
                ll_blue.visibility = View.GONE
                progress_bar.progress = 66
            }
            //连接成功
            STEP_CONNECT_SUCCESS -> {
                Log.i(TAG, "连接成功: ")
                connect_failed_layout.visibility = View.GONE
                fragment_container.visibility = View.GONE
                ll_pen_connect.visibility = View.VISIBLE
                ll_connect.visibility = View.VISIBLE
                iv_connect.visibility = View.VISIBLE
                ll_connect_status.visibility = View.GONE
                tv_pen_name.text = PenManager.instance.getConnectedPen()!!.name
                tv_mac_address.text = PenManager.instance.getConnectedPen()!!.macAddress
                tv_hint.text = getText(R.string.label_connect_pen_hint_3)
                tv_connect.text = getText(R.string.label_connect_pen_hint_3_icon)
                iv_connect.setBackgroundResource(R.drawable.connection_success)
                tv_hint.setTextColor(ContextCompat.getColor(this, R.color.connect_pen_success_hint))
                tv_sub_hint.text = getText(R.string.label_connect_pen_sub_hint_3)
                ll_blue.visibility = View.GONE
                progress_bar.progress = 100
                if (!isRegister) {
                    PenManager.instance.registerDataCallback(penCallback)
                    isRegister = true
                }
                LoadingView.dismissLoadingView()
            }
            //连接失败
            STEP_CONNECT_FAILED -> {
                supportFragmentManager.popBackStackImmediate()
                iv_connect.visibility = View.VISIBLE
                ll_connect_status.visibility = View.GONE
                ll_connect.visibility = View.VISIBLE
                tv_hint.text = getText(R.string.label_connect_pen_hint_4)
                tv_connect.text = getText(R.string.label_connect_pen_hint_4_icon)
                iv_connect.setBackgroundResource(R.drawable.connection_fails)
                tv_hint.setTextColor(ContextCompat.getColor(this, R.color.connect_pen_failed_hint))
                tv_sub_hint.text = getText(R.string.label_connect_pen_sub_hint_4)
                ll_blue.visibility = View.GONE
                progress_bar.progress = 100
                connect_failed_layout.visibility = View.VISIBLE
                connect_pen_introduce_layout.visibility = View.GONE
                LoadingView.dismissLoadingView()
            }
            STEP_DISCONNECT -> {
                supportFragmentManager.popBackStackImmediate()
                iv_connect.visibility = View.VISIBLE
                ll_connect_status.visibility = View.GONE
                ll_connect.visibility = View.VISIBLE
                tv_hint.text = getText(R.string.label_connect_pen_hint_5)
                tv_connect.text = getText(R.string.label_connect_pen_hint_5_icon)
                iv_connect.setBackgroundResource(R.drawable.connection_fails)
                tv_hint.setTextColor(ContextCompat.getColor(this, R.color.connect_pen_failed_hint))
                tv_sub_hint.text = getText(R.string.label_connect_pen_sub_hint_4)
                ll_blue.visibility = View.GONE
                progress_bar.progress = 100
                connect_failed_layout.visibility = View.VISIBLE
                connect_pen_introduce_layout.visibility = View.GONE
                LoadingView.dismissLoadingView()
            }
        }
    }

    private val penCallback: (DotUnit) -> Boolean = {
        //把在新页面注册回调成功之前把点先缓存下来
        PenManager.instance.cacheDotTemporary(it)
        startActivity(Intent(this, EditNoteActivity::class.java))
        finish()
        true
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = [(Tag(PenBusTag.CONNECT_STATE))]
    )
    @Suppress("unused")
    fun onConnectStateChanged(connectState: PenConnectState) {
        PenLog.d("connectState=$connectState")
        when (connectState) {
            PenConnectState.CONNECTED -> {
                PenScanner.instance.stopScan()
                changeStep(STEP_CONNECT_SUCCESS, true)
            }
            PenConnectState.CONNECT_FAILED -> {
                changeStep(STEP_CONNECT_FAILED, true)
            }
            PenConnectState.DISCONNECTED -> {
                Log.i(TAG, "onConnectStateChanged: 断开")
                changeStep(STEP_DISCONNECT, true)
            }
            else -> {
            }
        }
        LoadingView.dismissLoadingView()
    }

    /**
     * 添加一个Fragment
     * @param containerId
     * @param fragment
     * @param tag
     */
    private fun addFragment(containerId: Int, fragment: Fragment, tag: String) {
        val fragmentTransaction = supportFragmentManager.beginTransaction()
        fragmentTransaction.add(containerId, fragment, tag)
        fragmentTransaction.addToBackStack(tag)
        fragmentTransaction.commit()
    }

    private fun detachFragment(fragment: Fragment) {
        val fragmentTransaction = supportFragmentManager.beginTransaction()
        fragmentTransaction.detach(fragment)
        fragmentTransaction.commit()
    }

    /**
     * 替换Fragment
     * @param containerId
     * @param fragment
     * @param tag
     */
    fun replaceFragment(containerId: Int, fragment: Fragment, tag: String) {
        supportFragmentManager.popBackStackImmediate()
        addFragment(containerId, fragment, tag)
    }

    override fun onBackPressed() {
        when (curStep) {
            STEP_PREPARE -> finish()
            STEP_SEARCH_AND_CONNECT -> changeStep(--curStep, false)
            STEP_CONNECT_SUCCESS -> {
                PenManager.instance.disConnect()
                changeStep(--curStep, false)
            }
            STEP_CONNECT_FAILED -> {
                curStep -= 2
                changeStep(curStep, false)
            }
        }
    }

    private var isHasAlwaysPermission = false

    override fun onResume() {
        super.onResume()
        if(isHasAlwaysPermission){
            finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        RxBus.get().unregister(this)
        ServiceDialog.dismissDialog()
        PenManager.instance.startAutoConnectTask()

        if (isRegister) {
            PenManager.instance.unRegisterDataCallback(penCallback)
            isRegister = false
        }
    }

}
